import { defineStore } from 'pinia'
import { loginInfo } from '@/service/village'

// 用来存放用户信息
export const useUserStore = defineStore('user', {
  state: () => {
    return {
      userInfo: sessionStorage.getItem('user')
        ? JSON.parse(decodeURIComponent(sessionStorage.getItem('user')))
        : {}
    }
  },
  getters: {
    getUserInfo: (state) => {
      return state.userInfo
    },
  },
  actions: {
    setUserInfo(data) {
      sessionStorage.setItem('user', encodeURIComponent(JSON.stringify(data)))
      this.userInfo = data
    }
  }
})

// 用来存放用户信息
export const useLoginStore = defineStore('loginInfo', {
  state: () => {
    return {
      loginInfo: sessionStorage.getItem('loginInfo')
        ? JSON.parse(decodeURIComponent(sessionStorage.getItem('loginInfo')))
        : {}
    }
  },
  getters: {
    getLoginInfo: (state) => {
      return state.loginInfo
    },
  },
  actions: {
    async setLoginInfo() {
      try {
        // 2.市级
        // 3.区级
        // 4.街道
        // 5.社区村
        // 6.村民自查
        const result = await loginInfo()
        const data = {
          ...result.data,
          regionCode: result.data?.roletype === 2 ? result?.data?.citydm
            : result?.data?.roletype === 3 ? result?.data?.xzqdm
              : result?.data?.roletype === 4 ? result?.data?.towndm
                : result?.data?.roletype === 5 ? result?.data?.villagedm
                  : '',
          region: result.data?.roletype === 2 ? result?.data?.city
            : result?.data?.roletype === 3 ? `${result?.data?.city}-${result.data?.xzq}`
              : result?.data?.roletype === 4 ? `${result?.data?.city}-${result.data?.xzq}-${result?.data?.town}`
                : result?.data?.roletype === 5 ? `${result.data?.xzq}-${result?.data?.town}-${result?.data?.village}`
                  : ''
        }
        sessionStorage.setItem('loginInfo', encodeURIComponent(JSON.stringify(data)))
        this.loginInfo = data
      } catch (e) {
        //
      }
    }
  }
})
